//app.js
const userService = require('./services/userService');
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function (resda) {
          wx.getUserInfo({
            success: function (res) {
              var user = wx.getStorageSync('user');
              if(!user) {
                var user = res.userInfo;
                user.code = resda.code;
                user.rawData = res.rawData;
                user.encryptedData = res.encryptedData;
                user.iv = res.iv;
                user.signature = res.signature;
                wx.setStorageSync('user',user);
                wx.getLocation({
                  success:function(data) {
                    var latitude = data.latitude;
                    var longitude = data.longitude;
                    that.setUserOpenId(res.encryptedData,res.iv,res.signature,resda.code,res.rawData,user,cb,latitude,longitude); 
                  },
                  fail: function(error) {
                    that.setUserOpenId(res.encryptedData,res.iv,res.signature,resda.code,res.rawData,user,cb); 
                  }
                });
                 
              } else {
                 that.globalData.userInfo = res.userInfo
                 typeof cb == "function" && cb(that.globalData.userInfo)
              }
            },
            fail:function(res) {
              wx.showModal({
                title: '是否要打开设置页面重新授权',
                content: '需要获取您的公开信息（昵称、头像等），请到小程序的设置中打开用户信息授权',
                confirmText: '去设置',
                success: function(result){
                  //用户点击去设置打开设置页面
                  if(result.confirm) {
                     wx.openSetting({
                      success:function(res) {
                        if(that.globalData.qrcode) {
                          wx.redirectTo({
                            url: '/pages/activity/activity?qrcode=' + that.globalData.qrcode
                          });
                        } else {
                          wx.redirectTo({
                            url: '/pages/index/index'
                          });
                        }
                        
                      }
                    });
                  }
                  //用户点击取消按钮
                  if(result.cancel) {
                    wx.showToast({
                      title: '请先授权才能使用后续功能！',
                      complete: function(){
                        wx.openSetting({
                          success:function() {
                            if(that.globalData.qrcode) {
                              wx.redirectTo({
                                url: '/pages/activity/activity?qrcode=' + that.globalData.qrcode
                              });
                            } else {
                              wx.redirectTo({
                                url: '/pages/index/index'
                              });
                            }
                            
                          }
                        });
                      }
                    });
                  }
                 
                },
                fail: function(){

                }
              });
              
            }
          })
        }
      })
    }
  },
  setUserOpenId(encryptedData,iv,signature,code,rawData,user,cb,latitude,longitude){
    var params = {};
    params.encryptedData = encryptedData;
    params.iv = iv;
    params.signature = signature;
    params.code = code;
    params.rawData = rawData;
    if(latitude) {
      params.lat = latitude;
    }
    if(longitude) {
      params.lng = longitude;
    }
    if(this.globalData.activity_id) {
      params.activity_id = this.globalData.activity_id;
    }

    if(this.globalData.mid) {
      params.mid = this.globalData.mid;
    }

    if(this.globalData.qrcode) {
      params.qrcode = this.globalData.qrcode;
    }
    userService.login(params).then((data) => {
      if(data.code == 0) {
        wx.showToast({
          title: '登录失败' + data.msg
        })
        return;
      }
      user.openid = data.data.openid;
      wx.setStorageSync('user', user);//存储openid   
      typeof cb == "function" && cb(user) 
      }, (error) => {
    });
  },
  bindScanCode: function(callback) {
    var that = this; 
    wx.scanCode({
      success: function(res){
        var url = res.result;
        try {
          url = url.substring(url.lastIndexOf('/') + 1); 
          console.info(url);
          wx.navigateTo({
            url: '/pages/activity/activity?qrcode=' + url
          });
        } catch(e) {
          wx.showToast('二维码无效！');
        }
        
      }
    });
  },
   //修改tabBar的active值  
  editTabBar: function () {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1]; 
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true;//根据页面地址设置当前页面状态  
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  globalData:{
    activity_id: null,
    mid: null,
    qrcode: null,
    userInfo:null,
    //配置tabBar  
    tabBar: {
      "color": "#9E9E9E",
      "selectedColor": "#f00",
      "backgroundColor": "#fff",
      "borderStyle": "#ccc",
      "list": [
        {
          "pagePath": "/pages/index/index",
          "text": "首页",
          "iconPath": "/resources/home.png",
          "selectedIconPath": "/resources/home_sel.png",
          "selectedColor": "#4EDF80",
          active: false,
          type: 'url'
        },
        {
          "text": "扫码领奖",
          "iconPath": "/resources/saoma.png",
          "selectedIconPath": "/resources/saoma_sel.png",
          "selectedColor": "#4EDF80",
          active: false,
          type:'scanCode'
        },
        {
          "pagePath": "/pages/message/message",
          "text": "消息",
          "iconPath": "/resources/msg.png",
          "selectedIconPath": "/resources/msg_sel.png",
          "selectedColor": "#4EDF80",
          active: false,
          type: 'url'
        },
        {
          "text": "客服",
          "iconPath": "/resources/kefu.png",
          "selectedIconPath": "/resources/kefu_sel.png",
          "selectedColor": "#4EDF80",
          active: false,
          type: 'kefu'
        }
      ],
      "position": "bottom"
    }  
  }
})